#include "singleapp.h"
#include "funcmgr.h"
#include <QWidget>

SingleApplication::SingleApplication(int &Argc, char **Argv)
    : QApplication(Argc, Argv)
    , InRun(false)
    , LocalServer(Q_NULLPTR)
    , MainWindow(Q_NULLPTR)
{
    ServerName = QString("Client-AFK-DreamLocalSocketOneCheck") + AppName;
    InitLocalConnection();
}

bool SingleApplication::IsRun()
{
    return InRun;
}

void SingleApplication::NewLocalConnection()
{
    if (MainWindow != Q_NULLPTR)
        sFunc->DoAtTopWindow(MainWindow);
}

void SingleApplication::InitLocalConnection()
{
    InRun = false;

    QLocalSocket CSocket;
    CSocket.connectToServer(ServerName);
    if (CSocket.waitForConnected(3000))
    {
        InRun = true;
        return;
    }

    NewLocalServer();
}

void SingleApplication::NewLocalServer()
{
    LocalServer = new QLocalServer(this);
    QObject::connect(LocalServer, SIGNAL(newConnection()), this, SLOT(NewLocalConnection()));
    if (!LocalServer->listen(ServerName))
    {
        if (LocalServer->serverError() == QAbstractSocket::AddressInUseError)
        {
            QLocalServer::removeServer(ServerName);
            LocalServer->listen(ServerName);
        }
    }
}
